package com.clickpaas.governmentcloud.controller.policycontroller;

import com.alibaba.fastjson.JSON;
import com.clickpaas.governmentcloud.common.ConstantExt;
import com.clickpaas.governmentcloud.common.ServerResponse;
import com.clickpaas.governmentcloud.common.TokenCommon;
import com.clickpaas.governmentcloud.entity.policyEntity.PolicyEntity;
import com.clickpaas.governmentcloud.service.policymatchextservice.MatchExtMainService;
import com.clickpaas.governmentcloud.service.policyservice.PolicyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Api(description = "政策匹配")
@RestController
@RequestMapping(value = "/policy")
@Slf4j
public class PolicyController {

    @Autowired
    PolicyService policyService;
    @Autowired
    MatchExtMainService matchExtMainService;

    @ApiOperation(value = "精确匹配", notes = "精确匹配")
    @PostMapping(value = "/exactMatching")
//	@Logger(description = "精确匹配")
    public ServerResponse<?> exactMatching(@RequestParam(value = "token", required = false) String token, @RequestBody PolicyEntity policy) {
        String s = JSON.toJSONString(policy);
        //log.info("传来的参数是：{}", s);
        ServerResponse<?> serverResponse = ServerResponse.createError("失败");
        try {
            boolean tokenEffect = TokenCommon.isTokenEffect(token);
            if (tokenEffect) {
                policy.setCorpName(TokenCommon.getCorpNameByToken(token));
                //政策匹配前数据处理
                matchExtMainService.dealOldData(policy);
                //serverResponse = policyService.matchHiTech(policy);
                /**
                 * 政策匹配
                 */
                policy.setTypeofDataSource(ConstantExt.USER_PROCESSING);
                serverResponse = matchExtMainService.exactMultiThreadExecutMatchPolicy(policy, null);
            } else {
                serverResponse = ServerResponse.createError("403", "toekn校验失败,请检查token是否为空值");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return serverResponse;
    }

    @ApiOperation(value = "查询政策列表", notes = "查询政策列表")
    @GetMapping(value = "/searchMatchingResult")
    public ServerResponse<?> searchMatchingResult(@ApiParam(value = "pageNum") @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                                                  @ApiParam(value = "pageSize") @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
                                                  @ApiParam(value = "政策名称模糊查询") @RequestParam(value = "policiesName", required = false) String policiesName,
                                                  @ApiParam(value = "token") @RequestParam(value = "token" , required = false) String token) {
        ServerResponse<?> serverResponse = ServerResponse.createError("失败");
        try {
            boolean tokenEffect = TokenCommon.isTokenEffect(token);
            if (tokenEffect) {
                String corpName = TokenCommon.getCorpNameByToken(token);
                serverResponse = policyService.searchMatchingResult(pageNum, pageSize, policiesName, corpName);
            } else {
                serverResponse = ServerResponse.createError("403", "toekn校验失败,请检查token是否为空值");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return serverResponse;
    }

    @ApiOperation(value = "快速匹配", notes = "快速匹配")
    @GetMapping(value = "/fastMatching")
    public ServerResponse<?> fastMatching(@ApiParam(value = "token") @RequestParam(value = "token", required = false) String token) {
        ServerResponse<?> serverResponse = ServerResponse.createError("失败");
        try {
            boolean tokenEffect = TokenCommon.isTokenEffect(token);
            if (tokenEffect) {
                //serverResponse = policyService.fastMatching(token);
                /**
                 * 查询政策
                 */
                serverResponse = matchExtMainService.fastMutiThreadExecutMatchPolicy(token);
            } else {
                serverResponse = ServerResponse.createError("403", "toekn校验失败,请检查token是否为空值");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return serverResponse;
    }

//	@ApiOperation(value = "导出", notes = "导出")
//	@GetMapping(value = "/export")
//	public void exportAttachment(@ApiParam(value = "附件名称") @RequestParam(value = "attachmentName") String attachmentName,
//			@ApiParam(value = "附件链接") @RequestParam(value = "attachmentUrl") String attachmentUrl, HttpServletResponse response) {
//
//		// 记录开始下载的时间
//		long begin_time = new Date().getTime();
//		attachmentUrl = "https://img.successchannel.net/29862/K39410/20201113100814JmLLJK.pdf?attname=%E2%80%9C%E4%B8%93%E7%B2%BE%E7%89%B9%E6%96%B0%E2%80%9D%E4%B8%AD%E5%B0%8F%E4%BC%81%E4%B8%9A%E7%94%B3%E6%8A%A5%EF%BC%88%E5%A4%8D%E6%A0%B8%EF%BC%89.pdf&fileId=3ae02e21-5e6b-48f2-b57b-39acdba43ff2&ext=pdf";
//		attachmentUrl = "https://img.successchannel.net/29862/K39410/20201113100814JmLLJK.pdf?attname=%E2%80%9C%E4%B8%93%E7%B2%BE%E7%89%B9%E6%96%B0%E2%80%9D%E4%B8%AD%E5%B0%8F%E4%BC%81%E4%B8%9A%E7%94%B3%E6%8A%A5%EF%BC%88%E5%A4%8D%E6%A0%B8%EF%BC%89.pdf";
//		attachmentUrl = "https://img.successchannel.net/29862/K39410/20201113100814JmLLJK.pdf";
//		URL url = null;
//		// 获取连接
//		URLConnection conn = null;
//		InputStream inputStream = null;
//		InputStreamReader isr = null;
//		BufferedReader br = null;
//		BufferedWriter bw = null;
//		try {
//			url = new URL(attachmentUrl);
//			conn = url.openConnection();
//			conn.connect();
//			inputStream = conn.getInputStream();
//			
//			response.reset();
////			response.setContentType("application/octet-stream; chartset=utf-8");
//			response.setContentType("application/x-msdownload");
//			response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(attachmentName, "UTF-8"));
//			
//			isr = new InputStreamReader(inputStream);
//			br = new BufferedReader(isr);
//			
//			
//			bw = new BufferedWriter(response.getWriter());
//			String line;
//			while((line = br.readLine()) != null) {
//				bw.write(line);
//				bw.newLine();
//			}
//			bw.flush();
//		} catch (Exception e1) {
//			e1.printStackTrace();
//		} finally {
//			try {
//				
//				if(inputStream != null) {
//					inputStream.close();
//				}
//				if(isr != null) {
//					isr.close();
//				}
//				
//				if(bw != null) {
//					bw.close();
//				}
//				if(br != null) {
//					br.close();
//				}
//			
//			} catch (Exception e2) {
//				e2.printStackTrace();
//			}
//		}
//	
//	}
//	
//	@ApiOperation(value = "导出2", notes = "导出2")
//	@GetMapping(value = "/export2")
//	public void exportAttachment2(@ApiParam(value = "附件名称") @RequestParam(value = "attachmentName") String attachmentName,
//			@ApiParam(value = "附件链接") @RequestParam(value = "attachmentUrl") String attachmentUrl, HttpServletResponse response) {
//		
//		
//		attachmentUrl = "https://img.successchannel.net/29862/K39410/20201113100814JmLLJK.pdf?attname=%E2%80%9C%E4%B8%93%E7%B2%BE%E7%89%B9%E6%96%B0%E2%80%9D%E4%B8%AD%E5%B0%8F%E4%BC%81%E4%B8%9A%E7%94%B3%E6%8A%A5%EF%BC%88%E5%A4%8D%E6%A0%B8%EF%BC%89.pdf&fileId=3ae02e21-5e6b-48f2-b57b-39acdba43ff2&ext=pdf";
//		attachmentUrl = "https://img.successchannel.net/29862/K39410/20201113100814JmLLJK.pdf";
//		URL url = null;
//		// 获取连接
//		URLConnection conn = null;
//		InputStream inputStream = null;
//		BufferedInputStream bis = null;
//	    BufferedOutputStream bos = null;
//		try {
//			url = new URL(attachmentUrl);
//			conn = url.openConnection();
//			conn.connect();
//			inputStream = conn.getInputStream();
//			
//			response.reset();
//			response.setContentType("application/x-msdownload");
//	        response.setHeader(
//	                "Content-disposition",
//	                "attachment; filename="
//	                        + new String(attachmentName.getBytes("GBK"),
//	                        "ISO8859-1"));
//			
//	        bis = new BufferedInputStream(inputStream);
//	        bos = new BufferedOutputStream(response.getOutputStream());
//	        byte[] buff = new byte[2048];
//	        int bytesRead;
//	        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
//	            bos.write(buff, 0, bytesRead);
//	        }
//			
//			
//		} catch (Exception e1) {
//			e1.printStackTrace();
//		} finally {
//			try {
//				
//				if(inputStream != null) {
//					inputStream.close();
//				}
//				if (bis != null)
//	                bis.close();
//	            if (bos != null)
//	                bos.close();
//	            
//			} catch (Exception e2) {
//				e2.printStackTrace();
//			}
//		}
//	
//	}
//	
//	@ApiOperation(value = "导出3", notes = "导出3")
//	@GetMapping(value = "/export3")
//	public void exportAttachment3(@ApiParam(value = "附件名称") @RequestParam(value = "attachmentName") String attachmentName,
//			@ApiParam(value = "附件链接") @RequestParam(value = "attachmentUrl") String attachmentUrl, HttpServletResponse response) throws IOException {
//		
//		attachmentUrl = "https://img.successchannel.net/29862/K39410/20201113100814JmLLJK.pdf";
//		
//		ServletOutputStream out = null;
//		InputStream inputStream = null;
//		
//		try {
//			URL url = new URL(attachmentUrl);
//			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//			conn.setConnectTimeout(3 * 1000);
//			 //防止屏蔽程序抓取而返回403错误
//			conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//			inputStream = conn.getInputStream();
//			
//		    /**
//             * 输出文件到浏览器
//             */
//	          int len = 0;
//	          // 输出 下载的响应头，如果下载的文件是中文名，文件名需要经过url编码
//	          response.setContentType("application/x-download");
//	          response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(attachmentName, "UTF-8"));
//	          response.setHeader("Cache-Control", "no-cache");
//	          out = response.getOutputStream();
//	          byte[] buffer = new byte[1024];
//	          while ((len = inputStream.read(buffer)) > 0) {
//	              out.write(buffer, 0, len);
//	          }
//	          out.flush();
//			
//		} catch (Exception e) {
//			e.printStackTrace();
//		} finally {
//	          if (inputStream != null) {
//	              try {
//	                  inputStream.close();
//	              } catch (Exception e) {
//	              }
//	          }
//	          if (out != null) {
//	              try {
//	                  out.close();
//	              } catch (Exception e) {
//	              }
//	          }
//	      }
//	}
//	
//	
//	/**
//     * 从输入流中获取字节数组
//     * @param inputStream
//     * @return
//     * @throws IOException
//     */
//    public static  byte[] readInputStream(InputStream inputStream) throws IOException {
//        byte[] buffer = new byte[1024];
//        int len = 0;
//        ByteArrayOutputStream bos = new ByteArrayOutputStream();
//        while((len = inputStream.read(buffer)) != -1) {
//            bos.write(buffer, 0, len);
//        }
//        bos.close();
//        return bos.toByteArray();
//    }
}
